<?php
// +-------------------------------------------------------------------
// |
// +-------------------------------------------------------------------
// | Copyright (c) 2009-2016 All rights reserved.
// +-------------------------------------------------------------------
namespace Service\User;

class RedPacketsLog extends \Service\Common\BaseModel
{
    protected $name = 'red_packets_log';

    //订单使用红包
    public function useRedInOrder($uid, $order_no, $money)
    {
        $this->_add($uid, $order_no, $money, 0);
        $update = M('user')->save([
            'uid' => $uid,
            'red_packets' => ['exp', "red_packets-$money"]
        ]);
        if ($update === false) {
            throw new \Exception("可用红包更新失败");
        }
    }

    //取消订单恢复红包
    public function backRedByCancel($uid, $order_no, $money)
    {
        $this->_add($uid, $order_no, $money, 1);
        $update = M('user')->save([
            'uid' => $uid,
            'red_packets' => ['exp', "red_packets+$money"]
        ]);
        if ($update === false) {
            throw new \Exception("可用红包更新失败");
        }
    }

    public function _add($uid, $order_no, $money, $type)
    {
        $insert_id = $this->add([
            'type' => $type,
            'uid' => $uid,
            'order_no' => $order_no,
            'money' => $money,
            'create_time' => date('Y-m-d H:i:s'),
        ]);

        if (!$insert_id) {
            throw new \Exception("红包使用记录插入失败");
        }

    }
}